package org.example.node;

/**
 * @author liyishan
 * @date 2024/3/13 11:48
 * @apiNote
 */

public class Test00002AddTwoNumbers {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null, tail = null;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int n1 = l1 == null ? 0 : l1.val;
            int n2 = l2 == null ? 0 : l2.val;
            int sum = n1 + n2 + carry;
            if (head == null) {
                head = tail = new ListNode(sum % 10);
            } else {
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }
            carry = sum / 10;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry > 0) {
            tail.next = new ListNode(carry);
        }
        return head;
    }

    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        if(head1 == null){
            return head2;
        }
        if(head2 == null){
            return head1;
        }
        head1 = reverse(head1);
        head2 = reverse(head2);
        ListNode head = null;
        ListNode tail = null;
        int carry = 0;
        while(head1 != null || head2 != null){
            int n1 = head1 == null ? 0:head1.val;
            int n2 = head2 == null ? 0:head2.val;
            int sum = n1 + n2+carry;
            if(head == null){
                head = tail = new ListNode(sum %10);
            }else{
                tail.next = new ListNode(sum %10);
                tail = tail.next;
            }
            carry = sum /10;
            if(head1 != null){
                head1 = head1.next;
            }
            if(head2 != null){
                head2 = head2.next;
            }
        }
        if(carry > 0){
            tail.next = new ListNode(carry);
        }
        return reverse(head);

    }

    public ListNode reverse(ListNode head){
        ListNode pre = null;
        ListNode cur = head;
        while(cur != null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}
